<template>
	<view v-if="loaded" class="cat2bug-body">
		<page-header :team-id="teamId" :disabled="false" :show-back-button="true"></page-header>
		<page-body
			@scrolltolower="handleLowerRefresher"
			@scrolltoupper="handleToupperRefresher"
			@refresherrefresh="handlePullRefresher"
			:refresher-enabled="refresherEnabled"
			:refresher-triggered="refresherTriggered"
		>
			<template v-slot:content>
				<view class="tab-content col full-width" v-if="loaded">
					<uni-section :title="$t('defect.existing-tab')" type="line">
						<defect-tab-bar class="padding20" :tabs="tabs" @input="handleClickTab" @sort-change="getDefectConfig"></defect-tab-bar>
					</uni-section>
					<uni-section :title="$t('defect.new-tab')" type="line">
						<view class="col full-width padding20">
							<uni-forms ref="form" :modelValue="form" label-position="left" :rules="rules">
								<uni-forms-item :label="$t('defect.tab-name')" name="tabName" required>
									<uni-easyinput
									  v-model="form.tabName"
									  :placeholder="$t('defect.enter-tab-name')"
									  maxlength="32"
									  clearable></uni-easyinput>
								</uni-forms-item>
								<uni-forms-item :label="$t('defect.title')" name="defectName">
									<uni-easyinput
									  v-model="form.config.defectName"
									  :placeholder="$t('defect.enter-like-title')"
									  maxlength="128"
									  clearable
									/>
								</uni-forms-item>
								<uni-forms-item :label="$t('defect.my-following')">
									<switch :checked="defectCollect" @change="handleCollectChange" />
								</uni-forms-item>
								<uni-forms-item :label="$t('defect.type')" name="defectType">
									<defect-type-picker v-model="form.config.defectType" :type-list="config.types"></defect-type-picker>
								</uni-forms-item>
								<uni-forms-item :label="$t('defect.state')" name="defectState">
									<defect-state-picker v-model="form.config.params.defectStates" :state-list="config.states"></defect-state-picker>
								</uni-forms-item>
								<uni-forms-item :label="$t('module')" name="moduleId">
									<module-picker v-model="form.config.moduleId" :project-id="form.projectId" :is-edit="false" size="medium" />
								</uni-forms-item>
								<uni-forms-item :label="$t('version')" name="moduleVersion">
									<uni-easyinput
									  v-model="form.config.moduleVersion"
									  :placeholder="$t('defect.enter-version')"
									  maxlength="64"
									  clearable
									/>
								</uni-forms-item>
								<uni-forms-item :label="$t('handle-by')" name="handleBy">
									<member-picker
									  v-model="form.config.handleBy"
									  :placeholder="$t('defect.select-handle-by').toString()"/>
								</uni-forms-item>
							</uni-forms>
						</view>
					</uni-section>
				</view>
			</template>
		</page-body>
		<page-footer>
			<button class="full-width" type="primary" @click="handleAddTag">{{$t('create')}}</button>
		</page-footer>
	</view>
</template>

<script>
	import { delTabs, addTabs } from "@/api/system/DefectTabs";
	import { configDefect } from "@/api/system/defect";
	import {getDefectTempTab, removeDefectTempTab} from "@/utils/defect";
	import ModulePicker from "@/components/module/module-picker/index.vue"
	import MemberPicker from "@/components/member/member-picker/index.vue"
	import DefectTypePicker from "@/subpackage/components/defect/defect-type-picker/index.vue"
	import DefectStatePicker from "@/subpackage/components/defect/defect-state-picker/index.vue"
	import DefectTabBar from "@/components/defect/defect-tab-bar/index.vue"
	/** 记录Tab标签选项 */
	const DEFECT_TAB_CACHE_KEY='defect-tab';
	/** 名称等于所有选项的name */
	const ALL_TAB_NAME = 'all-tab';
	
	export default {
		name: 'DefectTab',
		components: { ModulePicker, MemberPicker, DefectTypePicker, DefectStatePicker, DefectTabBar },
		data() {
			return {
				tabIndex: 0,
				// 缺陷配置
				config:{
					types: [],
					states: []
				},
				// 所有tab的名称
				allTab: ALL_TAB_NAME,
				// 当前缺陷的tab页名
				activeDefectTabName: ALL_TAB_NAME,
				defectCollect: false,
				// 新建标签的表单数据
				form: {
					config: {
						moduleId: null,
						handleBy: [],
						params: {
							collect: null,
							defectStates: []
						}
					}
				},
				rules: {
					tabName: {
						rules: [{
								required: true,
								errorMessage: this.$i18n.t('defect.enter-tab-name'),
							}
						]
					},
				}
			}
		},
		computed: {
			/** 是否加载完成  */
			loaded() {
				return (this.$i18n && this.$i18n.locale)?true:false;
			},
			/** 当前团队ID */
			teamId() {
				return this.$store.state.user.config.currentTeamId;
			},
			/** 当前项目名称 */
			projectId() {
			    return this.$store.state.user.config.currentProjectId;
			},
			/** 获取当前成员id */
			currentMemberId() {
				return this.$store.state.user.id;
			},
			/** 查询标签名称集合  */
			tabNames() {
				return [
					...(this.config&&this.config.tabs)?this.config.tabs.map(t=>t.tabName):[],
					...[this.$i18n.t('defect.all-defect')]
				]
			},
			tabs() {
				return (this.config&&this.config.tabs)?this.config.tabs:[];
			}
		},
		created() {
			this.getDefectConfig();
		},
		methods: {
			/** 重置表单  */
			reset() {
				this.form = {
					config: {
						moduleId: null,
						handleBy: [],
						params: {
							collect: null,
							defectStates: []
						}
					}
				}
			},
			/** 处理收藏选项改变事件  */
			handleCollectChange(val) {
				this.form.config.params.collect = (val.detail.value?1:0);
			},
			/** 处理弹框严码点击事件  */
			handlePopupMaskClick() {
				this.$emit('close');
			},
			/** 弹框的显示改变事件  */
			handlePopupChange(e) {
				if(e.show) {
					this.$emit('open');
				} else {
					this.handlePopupMaskClick();
				}
			},
			/** 打开弹框  */
			handleOpenPopup() {
				this.$refs.popup.open();
			},
			handleClosePopup() {
				this.$refs.popup.close();
			},
			/** 获取当前用户缺陷配置 */
			getDefectConfig() {
			  configDefect().then(res=>{
				this.config = res.data;
				// 如果页面传的参数有tab，代表有临时查询
				const tab = getDefectTempTab(); // 获取临时缓存tab
				if(tab){
				  // removeDefectTempTab();
				  this.config.tabs = this.config.tabs || [];
				  this.config.tabs.unshift(tab);
				  this.activeDefectTabName = tab.tabId+'';
				} else if(this.config.tabs) {
				  // 从本地缓存取激活的页标签名称
				  this.activeDefectTabName = uni.getStorageSync(DEFECT_TAB_CACHE_KEY); // || ALL_TAB_NAME;
				  // 查看所有页标签里是否保护激活页标签，如果没有，设置页标签为"全部"
				  if(!this.activeDefectTabName || this.config.tabs.filter(t=>t.tabId+''==this.activeDefectTabName).length==0) {
					this.activeDefectTabName = this.allTab;
				  }
				}
				// 执行激活页标签方法
				// this.selectDefectTabHandle();
			  })
			},
			/** 切换页标签 */
			selectDefectTabHandle() {
			  if(this.config && this.config.tabs) {
				let tab = this.config.tabs.find(t=>t.tabId==this.activeDefectTabName);
				if(tab && tab.config) {
				  tab.config.isAsc = 'desc';
				  tab.config.orderByColumn = 'updateTime';
				  if(!tab.config.params) {
					tab.config.params = {
					  defectStates: []
					};
				  }
				  this.queryParams = tab.config;
				} else {
				  this.reset();
				}
				this.handleQuery();
			  }
			  uni.setStorageSync(DEFECT_TAB_CACHE_KEY, this.activeDefectTabName);
			},
			/** 处理添加标签事件 */
			handleAddTag() {
				const self = this;
				this.$refs.form.validate().then(res=>{
					this.form.projectId = this.projectId;
					this.form.userId = this.currentMemberId;
					addTabs(this.form).then(res=>{
						uni.showToast({
							title: self.$i18n.t('create-success')
						});
						self.reset();
						self.getDefectConfig();
						uni.$emit('defect-tab-change');
					});
				}).catch(err =>{
					uni.showToast({
						icon: 'error',
						title: err.map(e=>e.errorMessage).join(';')
					})
				});
			},
			/** 处理删除标签事件 */
			handleClickTab(index, tag) {
				const self = this;
				uni.showModal({
					title: this.$i18n.t('prompted').toString(),
					content: this.$i18n.t('defect.delete-defect-tab').toString(),
					confirmText: this.$i18n.t('delete').toString(),
					cancelText: this.$i18n.t('cancel').toString(),
					success: function (res) {
						if (res.confirm) {
							delTabs(tag.tabId).then(res=>{
								uni.showToast({
									title: self.$i18n.t('delete-success')
								});
								self.getDefectConfig();
								uni.$emit('defect-tab-change');
							})
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.padding20 {
		padding: 0 20rpx;
	}
</style>